package com.mc.moring.view.mailautocomplete;

import android.widget.Filter;

import java.util.ArrayList;
import java.util.List;

public class CustomFilter extends Filter {
    private AutoCompleteAdapter adapter;

    String emails[] = new String[]{"@gmail.com","@yahoo.com","@ymail.com",
            "@live.com","@hotmail.com","@aol.com","@webmail.co.za","@vodamail.co.za","@iafrica.com"};
    public CustomFilter(AutoCompleteAdapter adapter){
        this.adapter = adapter;
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults fr = null;
        if (constraint != null && constraint.length() > 0) {
            // 检查输入的第一个字符是否是空格，是的话不进行邮箱建议
            if (constraint.charAt(0) == ' ') {
                return null;
            }
            // 检查输入中是否包含"@ "，如果包含则进行邮箱建议
            if (constraint != null && constraint.toString().contains("@"))
            {
                List<MailBean> result = getFilterdValues(constraint.toString());

                if (result != null)
                {
                    fr = new FilterResults();
                    fr.values = result;
                    fr.count = result.size();
                }
            }
        }


        return fr;
    }

    private List<MailBean> getFilterdValues(String string) {
        List<MailBean> list = new ArrayList<MailBean>();
        if(string.indexOf("@") == -1){
            for(int i = 0; i < emails.length;i++){
                MailBean mailBean = new MailBean();
                mailBean.setName(string+emails[i]);
                list.add(mailBean);
            }
        }
        if(string.indexOf("@") != -1){
            for(int i = 0; i < emails.length; i++){
                String last = string.substring(string.indexOf("@"));
                if(emails[i].contains(last)){
                    MailBean mailBean = new MailBean();
                    mailBean.setName(string.substring(0,string.indexOf("@"))+emails[i]);
                    list.add(mailBean);
                }

            }
        }
        return list;
    }

    @Override
    protected void publishResults(CharSequence constraint,
                                  FilterResults results) {
        adapter.clear();
        if (results != null)
        {
            if (results.values != null)
            {
                List<MailBean> items = (List<MailBean>) results.values;
                for (MailBean listItem : items) {
                    adapter.add(listItem);
                }

                if (items.size() > 0)
                {
                    adapter.notifyDataSetChanged();
                    return;
                }
            }
        }
        adapter.notifyDataSetInvalidated();
    }

}
